/*
 * @Author: 抱着羊啃 1437670973@qq.com
 * @Date: 2025-04-25 21:51:19
 * @LastEditors: 抱着羊啃 1437670973@qq.com
 * @LastEditTime: 2025-05-19 10:33:56
 * @FilePath: \demo1\src\main\java\org\example\demo1\servlets\LoginPage\LoginServlet.java
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package org.example.demo1.servlets.LoginPage;


import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.ibatis.session.SqlSession;
import org.example.demo1.DAO.RolePermissionDao;
import org.example.demo1.DAO.UserRoleDao;
import org.example.demo1.Entity.User;
import org.example.demo1.utils.MybatisUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import static org.example.demo1.utils.InquireTools.getUserInformation;

@WebServlet("/API/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求体解码
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        Map<String, Object> data = new HashMap<>();
        
        User user = getUserInformation(username);
        
        if (user == null) {
            //json格式
            data.put("status", "error");
            data.put("code", 400);
            data.put("message", "用户名不存在");
        } else {
            String ps = user.getPassword();
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            //方式一：getMapper
            UserRoleDao mapper = sqlSession.getMapper(UserRoleDao.class);
            RolePermissionDao mapper1=sqlSession.getMapper(RolePermissionDao.class);
            int user_id = user.getUser_id();
            //获取用户角色
            List<Integer> role = mapper.getRoleIdsByUserId(user_id);
            
            // 使用HashSet收集权限，自动去重
            Set<Integer> permissionSet = new HashSet<>();
            for (Integer role_id : role) {
                permissionSet.addAll(mapper1.getPermissionIdsByRoleId(role_id));
            }
            
            // 如果需要List类型，可以转换回来
            List<Integer> permission = new ArrayList<>(permissionSet);
            

            if (password.equals(ps)) {

                if (!permission.contains(8)) {
                    data.put("status", "success");
                    data.put("code", 201);
                    data.put("message", "操作成功");
                    HttpSession session = req.getSession();
                    session.setAttribute("user", user);
                    session.setAttribute("permission",permission);
                } else {
                    data.put("status", "success");
                    data.put("code", 200);
                    data.put("message", "操作成功");
                    HttpSession session = req.getSession();
                    session.setAttribute("user", user);
                    session.setAttribute("permission",permission);
                }
            } else {
                data.put("status", "success");
                data.put("code", 401);
                data.put("message", "用户名或密码错误");
            }
        }
        // 使用Gson或Jackson将对象转为JSON
        String json = new Gson().toJson(data);

        // 发送响应
        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
    }
}